package cn.lumora.strategy;

import cn.hutool.core.util.ObjectUtil;
import cn.lumora.controller.req.LoginRequest;
import cn.lumora.core.security.password.PasswordUtil;
import cn.lumora.core.security.rea.RSACipherUtil;
import cn.lumora.core.security.rea.RSAKeyStorageService;
import cn.lumora.core.security.token.TempTokenService;
import cn.lumora.pojo.*;
import cn.lumora.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 刘智超
 * 账号密码注册
 */
@Component("passwordRegisterStrategy")
@Slf4j
public class PasswordRegisterStrategy implements RegisterStrategy {

    /**
     * 玩家服务
     */
    private final PlayerService playerService;

    /**
     * 角色基础信息服务
     */
    private final CharacterBaseInfoService characterBaseInfoService;

    // 注入安全相关服务
    private final RSAKeyStorageService rsaKeyStorageService;
    private final TempTokenService tempTokenService;

    /**
     * 角色初始化服务
     */
    private final CharacterInitService characterInitService;

    @Autowired
    public PasswordRegisterStrategy(PlayerService playerService, CharacterBaseInfoService characterBaseInfoService, RSAKeyStorageService rsaKeyStorageService, TempTokenService tempTokenService, CharacterInitService characterInitService) {
        this.playerService = playerService;
        this.characterBaseInfoService = characterBaseInfoService;
        this.rsaKeyStorageService = rsaKeyStorageService;
        this.tempTokenService = tempTokenService;
        this.characterInitService = characterInitService;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String register(LoginRequest request) {
        try {
            log.info("使用账号密码注册");
            log.info("用户名：{}", request.getUsername());
            log.info("密码：{}", request.getPassword());

            // 2. 获取RSA私钥用于解密密码
            String privateKey = rsaKeyStorageService.getPrivateKey();
            if (privateKey == null) {
                throw new RuntimeException("RSA私钥不可用");
            }

            // 3. 使用私钥解密请求中的密码
            String decryptedPassword = null;
            try {
                decryptedPassword = RSACipherUtil.decryptWithPrivateKey(request.getPassword(), privateKey);
            } catch (Exception e) {
                log.error("解密密码失败:{}", e.getMessage());
                throw new RuntimeException(e.getMessage());
            }

            // 验证用户名是否已存在
            if (playerService.checkUsername(request.getUsername())) {
                throw new RuntimeException("用户名已存在");
            }
            // 新增玩家
            Player player = Player.builder()
                    .username(request.getUsername())
                    .password(PasswordUtil.hashPassword(decryptedPassword))
                    .build();
            boolean save = playerService.save(player);

            // 初始化角色信息
            String characterId = initCharacterBaseInfo(player.getId());

            // 初始化背包
            characterInitService.initCharacterInventory(characterId);

            // 初始化天赋
            characterInitService.initCharacterTalent(characterId);

            // 初始化境界
            characterInitService.initCultivationStage(characterId);

            return player.getId();
        } catch (Exception e) {
            log.error("注册失败", e);
            throw new RuntimeException("注册失败");
        }
    }


    /**
     * 初始化角色信息
     *
     * @param playerId 玩家id
     * @return 角色id
     */
    private String initCharacterBaseInfo(String playerId) {
        try {
            CharacterBaseInfo characterBaseInfo = CharacterBaseInfo.builder()
                    .playerId(playerId) // 玩家id
                    .name("角色" + System.currentTimeMillis())// 角色名称
                    .level(1) // 角色等级
                    .exp(0L) // 角色经验
                    .maxExp(100L) // 角色最大经验
                    .healthPoints(100) // 角色血量
                    .attackPower(10) //  角色攻击力
                    .defensePower(10) // 角色防御力
                    .gold(100) // 角色金币
                    .build();
            characterBaseInfo.setCreateTime(LocalDateTime.now());
            characterBaseInfo.setUpdateTime(LocalDateTime.now());
            characterBaseInfoService.save(characterBaseInfo);
            log.info("初始化角色信息成功");
            // 初始化成功返回角色id
            return characterBaseInfo.getId();
        } catch (Exception e) {
            log.error("初始化角色信息失败", e);
            throw new RuntimeException("初始化角色信息失败");
        }


    }

}
